package net.srt.quartz.api.data.access;

import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import net.srt.api.module.data.DataAccessApi;
import net.srt.api.module.data.constant.TaskType;
import net.srt.api.module.data.dto.DataAccessDto;
import net.srt.api.module.quartz.data.access.QuartzDataAccessApi;
import net.srt.framework.common.utils.Result;
import net.srt.quartz.entity.ScheduleJobEntity;
import net.srt.quartz.enums.ScheduleConcurrentEnum;
import net.srt.quartz.utils.ScheduleUtils;
import org.quartz.Scheduler;
import org.springframework.web.bind.annotation.RestController;

/**
 * 短信服务API
 *
 * @author 阿沐 babamu@126.com
 */
@RestController
@RequiredArgsConstructor
public class QuartzDataAccessApiImpl implements QuartzDataAccessApi {

	private final Scheduler scheduler;
	private final DataAccessApi dataAccessApi;

	@Override
	public Result<String> releaseAccess(Long id) {
		ScheduleJobEntity jobEntity = buildJobEntity(id);
		ScheduleUtils.createScheduleJob(scheduler, jobEntity);
		return Result.ok();
	}

	@Override
	public Result<String> cancleAccess(Long id) {
		ScheduleJobEntity jobEntity = buildJobEntity(id);
		ScheduleUtils.deleteScheduleJob(scheduler, jobEntity);
		return Result.ok();
	}

	@Override
	public Result<String> handRun(Long id) {
		ScheduleJobEntity jobEntity = buildJobEntity(id);
		ScheduleUtils.run(scheduler, jobEntity);
		return Result.ok();
	}


	private ScheduleJobEntity buildJobEntity(Long id) {
		DataAccessDto dataAccessDto = dataAccessApi.getById(id).getData();
		return ScheduleJobEntity.builder().jobName("DATA_ACCESS_" + id).customJobName(true).concurrent(ScheduleConcurrentEnum.NO.getValue())
				.beanName("dataAccessTask").method("syncData").jobGroup("DATA_ACCESS").saveLog(false).cronExpression(dataAccessDto.getCron())
				.params(String.valueOf(id)).once(TaskType.ONE_TIME_FULL_SYNC.getCode().equals(dataAccessDto.getTaskType())).build();
	}
}
